package com.neusoft.neu24.nep.role.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neusoft.neu24.nep.entity.ComonResult;
import com.neusoft.neu24.nep.role.entity.Sysnode;
import com.neusoft.neu24.nep.role.mapper.SysnodeMapper;
import com.neusoft.neu24.nep.role.service.ISysnodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统功能节点树 服务实现类
 * </p>
 *
 * @author 段静迪，duanjingdi@163.com
 * @since 2024-06-06
 */
@Service
public class SysnodeServiceImpl extends ServiceImpl<SysnodeMapper, Sysnode> implements ISysnodeService {

    @Override
    public ComonResult<Sysnode> selectAllByTree() {

        LambdaQueryWrapper<Sysnode> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.ne(Sysnode::getState, 0);
        List<Sysnode> sysnodes = getBaseMapper().selectList(lambdaQueryWrapper);

        Sysnode root =  list2Tree(sysnodes);
        return ComonResult.success(root);
    }

    private Sysnode list2Tree(List<Sysnode> sysnodes) {
//        1、寻找根节点
        Sysnode root = null ;
        for (Sysnode sysnode : sysnodes) {
            if(sysnode.getPid() == null){
                root =  sysnode;
                break;
            }
        }

//        填充根节点的孩子
        fillChildren( root , sysnodes );

        return   root;

    }

    private void fillChildren(Sysnode root, List<Sysnode> sysnodes) {
        if (root == null || sysnodes == null || sysnodes.size() == 0) {
            return;
        }
        if (root.getChildren() == null) {
            root.setChildren(new ArrayList<Sysnode>());
        }

        for (Sysnode sysnode : sysnodes) {
            if (sysnode.getPid() != null && sysnode.getPid().intValue() == root.getId().intValue()) {
                root.getChildren().add(sysnode);
            }
        }
//        递归填充孩子节点
        if (root.getChildren() == null ||  root.getChildren().size()== 0){
            return;
        }

        for (Sysnode sysnode : root.getChildren()) {
            fillChildren(sysnode, sysnodes);
        }
    }
}
